<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryData.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          node-key="id"
          :expand-on-click-node="false"
          highlight-current
          default-expand-all
          :data="depts"
          :props="{ label:'name' }"
          @current-change="treeChange"
        />
      </div>
      <div class="right">
        <el-row
          class="opeate-tools"
          type="flex"
          justify="end"
        >
          <el-button
            v-permission="'employee-add'"
            size="mini"
            type="primary"
            @click="$router.push('/employee/detail')"
          >添加员工</el-button>
          <el-button v-permission="'employee-import'" size="mini" @click="$refs.iptExcel.showExcelDialog=true">excel导入</el-button>
          <el-button v-permission="'employee-export'" size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column
            align="center"
            label="头像"
          >
            <template slot-scope="{row}">
              <el-avatar
                v-if="row.staffPhoto"
                :src="row.staffPhoto"
                :size="30"
              />
              <span
                v-else
                class="username"
              >{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
          />
          <el-table-column
            prop="mobile"
            label="手机号"
            sortable
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            sortable
          />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
          >
            <template slot-scope="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="departmentName"
            label="部门"
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            sortable
          />
          <el-table-column
            label="操作"
            width="280px"
          >
            <template slot-scope="{row}">
              <el-button
                v-permission="'employee-see'"
                size="mini"
                type="text"
                @click="$router.push('/employee/detail/'+row.id)"
              >查看</el-button>
              <el-button
                v-permission="'employee-assign'"
                size="mini"
                type="text"
                @click="openAssignRole(row.id)"
              >角色</el-button>&nbsp;
              <el-popconfirm
                title="确认删除吗?"
                @onConfirm="delRow(row.id)"
              >
                <el-button
                  slot="reference"
                  v-permission="'employee-del'"
                  size="mini"
                  type="text"
                >删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row
          style="height: 60px"
          align="middle"
          type="flex"
          justify="end"
        >

          <el-pagination
            :current-page.sync="queryData.page"
            :page-size="queryData.pagesize"
            layout="total,prev, pager, next"
            :total="total"
            background
            @current-change="currentChange"
          />

        </el-row>
      </div>
    </div>
    <!-- 导入Excel弹框 -->
    <import-excel ref="iptExcel" @updateList="initData" />
    <!-- 员工关联角色弹框 -->
    <assignRole ref="assignRole" />
  </div>
</template>

<script>
import { getDepartmentListApi } from '@/api/department'
import { transListToTreeData } from '@/utils'
import { delEmpApi, exportEmpApi, getEmpInfoApi, getEmpListApi } from '@/api/employee'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
import assignRole from './components/assign-role.vue'
export default {
  name: 'Employee',
  components: { importExcel, assignRole },
  data() {
    return {
      depts: [],
      // 列表查询参数
      queryData: {
        page: 1,
        pagesize: 10,
        keyword: '',
        departmentId: ''
      },
      // 表格数据
      list: [],
      // 总数
      total: 0
    }
  },
  async created() {
    await this.getDeptList()
    // initData里面queryData需要提交，需要用到departmentId,等到getDeptList结束
    this.initData()
  },
  methods: {
    // 获取组织架构
    async getDeptList() {
      // 请求数据
      const res = await getDepartmentListApi()
      // 赋值数据
      this.depts = transListToTreeData(res, 0)
      if (this.depts.length === 0) return
      // 设置默认的部门ID
      this.queryData.departmentId = this.depts[0].id
      // 树的第一个节点高亮(如何让树的某个节点选中呢？)
      // 等到DOM渲染完成之后做某个事情
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.depts[0].id)
      })
    },
    // 获取员工数据
    async initData() {
      // 请求数据
      const res = await getEmpListApi(this.queryData)
      // 加工数据
      // 赋值数据
      this.list = res.rows
      this.total = res.total
    },
    // 页码切换事件
    currentChange(val) {
      this.queryData.page = val
      this.initData()
    },
    // 树的高亮选中切换事件
    treeChange(val) {
      // val就是点击的行的数据
      this.queryData.departmentId = val.id
      this.queryData.page = 1
      this.initData()
    },
    // 输入框内容变化
    changeValue() {
      // 防抖优化
      if (this.timer) clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryData.page = 1
        this.initData()
      }, 300)
    },
    // 导出员工
    // 导出功能，我们发起导出请求，后端返回二进制blob数据流程
    // 我们在响应拦截器里面判断如果是文件流就直接返回
    // 通过 URL.createObjectURL(blob文件流) 生成预览地址
    // 生成一个a标签，将预览地址给href，模拟点击，实现自动下载
    async exportEmployee() {
      // 得到Blob数据
      const res = await exportEmpApi()
      console.log(res)
      // 将Blob数据转成地址，资源下载地址
      // #region
      // const url = URL.createObjectURL(res)
      // const a = document.createElement('a')
      // a.href = url
      // a.download = '员工信息.xlsx'
      // document.body.appendChild(a)
      // a.click()
      // document.body.removeChild(a)
      // #endregion
      // 通过插件完成
      //  FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(res, '员工信息.xlsx')
    },
    // 删除
    async delRow(id) {
      await delEmpApi(id)
      this.$message.success('删除成功')
      if (this.queryData.page > 1 && this.list.length === 1) this.queryData.page--
      this.initData()
    },
    // 打开关联角色弹框
    async openAssignRole(id) {
      // 根据ID查询该员工的信息，获取角色，赋给checkRole
      const res = await getEmpInfoApi(id)
      this.$refs.assignRole.userId = id
      this.$refs.assignRole.checkRole = res.roleIds
      this.$refs.assignRole.showDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
